/**
 * Author: Shen Yanqiu
 * Date: 2017-12-08
 * Time: 18:35
 *
 */
import { routerRedux } from "dva/router";
import modelExtend from 'dva-model-extend';
import { pageModel } from '../common';
import { message } from 'antd';
import { routerTool } from "utils";
import { getSchool, getCode, doRegister } from "../../services/register";

export default modelExtend(pageModel, {
  namespace: 'register',

  state: {
    school: {},
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        // console.log(location.query);
        if (location.pathname === routerTool.getPathByName('Register')) {
          dispatch({ type: 'getSchool' });
        }
      });
    },
  },

  effects: {
    // 获取学校
    * getSchool ({ payload = {} }, { call, put }) {
      const { success, results } = yield call(getSchool, { page: 1, limit: 10 });
      if (success && results) {
        yield put({
          type: 'update',
          payload: {
            school: results,
          },
        });
      }
    },
    // 注册获取验证码
    * getCode ({ payload: params }, { call, put }) {
      params.type = 'Register';
      const code = yield call(getCode, params);
      const { message: msg } = code;
      if (code.success) {
        message.success("验证码发送成功！");
        return;
      }
      message.error(msg || "验证码发送失败！");
    },
    // 执行注册
    * doRegister ({ payload: params }, { call, put }) {
      const registerInfo = yield call(doRegister, params);
      console.log(registerInfo);

      if (!registerInfo.success) {
        // console.log(registerInfo);
        message.error("注册失败，请检查输入是否正确！");
        return;
      }
      // console.log(registerInfo);
      message.success("注册成功，请登录！");
      yield put(
        routerRedux.push({ pathname: '/login' })
      );
    },
  },

  reducers: {
    update (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
});
